//
//  ArticleDetailsViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/22.
//

import UIKit
import WebKit

class ArticleDetailsViewController: BaseViewController {

    var emptyView: LYEmptyView!
    var cacheWebView: WKWebView!
    var tableView: BaseTableView!
    var dataArr: [CarDetailsContentModel] = []
    var id: String = ""
    var data: ArticleListModel!
    var titleStr: String = ""
    var progressView: UIProgressView! = {
        let tempProgressView = UIProgressView.init(frame: CGRect.init(x: 0, y: NavBarHight-2, width: kScreenWidth, height: 2))
        tempProgressView.backgroundColor = UIColor.white
        tempProgressView.progressTintColor = Theme.mainColor
        return tempProgressView
    }()
    var webBkgView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navBar.title = self.titleStr
        self.addInitNav()
        
        self.tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .grouped)
        self.tableView.register(ArticelTitleTableViewCell.self, forCellReuseIdentifier: "ArticelTitleTableViewCell")
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.backgroundColor = UIColor.init(hex: 0xF2F7FA)
        self.tableView.separatorStyle = .none
        self.tableView.estimatedRowHeight = 2
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.view.addSubview(self.tableView)
        
        webBkgView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 1))
        self.tableView.tableHeaderView = webBkgView
        let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 74))
        self.tableView.tableFooterView = footer
        self.tableView.tableFooterView?.isHidden = true
        
        self.addLoadMoreRefreash()
        self.setUpNoData()
        self.fetchGetAticleDetail()
        self.navBar.addSubview(self.progressView)
    }
    
    
    //导航栏
    func addInitNav() {
        //kScreenWidth - 104
        let shareBtn = UIButton(frame: CGRect(x: kScreenWidth - 44, y: NavBarHight - 35, width: 30, height: 30))
        shareBtn.setImage(UIImage(named: "icon_normal_share"), for: .normal)
        shareBtn.addTarget(self, action: #selector(shareBtnAntion), for: .touchUpInside)
        shareBtn.isHidden = false
        self.navBar.addSubview(shareBtn)
     
    }
    
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    ///离开页面
    override func didMove(toParentViewController parent: UIViewController?) {
        if parent == nil {
            self.cacheWebView?.scrollView.removeObserver(self, forKeyPath: "contentSize")
            self.cacheWebView?.reload() //后退时，暂这视频播放
        }
    }
    
    override func backAction() {
        self.cacheWebView?.reload()
        self.navigationController?.popViewController(animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    
    //分享
    @objc func shareBtnAntion(){
        let VC = ShareViewController()
        VC.titleStr = MMLocalizedString("share", comment: "分享")
        VC.isfaceBook = true
        //MMLocalizedString("share_article", comment: "我想与您分享以下文章") +
        VC.shareContent =  (self.data?.shareUrl ?? "")
        VC.shareUrl = self.data?.shareUrl ?? ""
        VC.modalPresentationStyle = .overFullScreen
        self.present(VC, animated: false, completion: nil)
    }
    
    
    
    //MARK: - 上拉加载更多
    private func addLoadMoreRefreash()  {
        self.tableView.mj_footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
            self.tableView.mj_footer.endRefreshing()
        })
    }
    
    ///获取详情信息
    func fetchGetAticleDetail() {
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.apiArticleDetail(param: ["id":self.id]), objectType: ArticleDetailModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! ArticleDetailModel
            if resultObj.code == "1" {
                self.data = resultObj.data
                self.dataArr = resultObj.data?.usedcars ?? []
                self.loadWebContent()
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
                self.emptyView?.titleStr = MMLocalizedString("no_more_data", comment: "暂时没有数据")
            }
            self.willShowEmptyView()
        } error: { err in
            self.emptyView?.titleStr = MMLocalizedString("no_more_data", comment: "暂时没有数据")
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
            self.willShowEmptyView()
        }
    }
    
    func willShowEmptyView() {
        if self.dataArr.count > 0 {
            self.emptyView.isHidden = true
        }else{
            self.emptyView.isHidden = false

        }
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_default_place", titleStr:"", detailStr: "", btnTitleStr: "") {
            
        }
        self.emptyView.clipsToBounds = true
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -50
        self.tableView.ly_emptyView = self.emptyView
        self.tableView.ly_emptyView?.isHidden = true
        
    }
    

    
    //计算webView
    private func loadWebContent() {
        if self.cacheWebView == nil {
            let configuretion = WKWebViewConfiguration.init()
            configuretion.preferences = WKPreferences()
            configuretion.preferences.minimumFontSize = 0
            configuretion.preferences.javaScriptEnabled = true
            configuretion.preferences.javaScriptCanOpenWindowsAutomatically = false
            configuretion.userContentController = WKUserContentController()
            configuretion.allowsPictureInPictureMediaPlayback = true
            //播放视频全屏
            configuretion.allowsInlineMediaPlayback = true
            //投屏按钮
            configuretion.allowsAirPlayForMediaPlayback = true
            configuretion.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.all
            
            cacheWebView = WKWebView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 0), configuration: configuretion)
            cacheWebView.navigationDelegate = self
            cacheWebView.uiDelegate = self
            if #available(iOS 11.0, *) {
                cacheWebView.scrollView.contentInsetAdjustmentBehavior = .never
            }
            cacheWebView.scrollView.isScrollEnabled = false
            cacheWebView.scrollView.showsHorizontalScrollIndicator = false
        }
        webBkgView.addSubview(self.cacheWebView)
        
        self.cacheWebView.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
        self.cacheWebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        
        //加载本地html
        let tempHtml = self.createHtmlContentString()
        self.cacheWebView.loadHTMLString(tempHtml, baseURL: nil)
    }
    
    ///组装Html标签
    func createHtmlContentString() -> String {
        var tempStr: String = ""
        //在这理处于是一下html5标签，适配手机设备，%在String(format:"%@")中会转化，所以单独给img{max-width:100%;}中的百分号一个%@
        if !(self.data.content ?? "").contains("<html") {
            let formatWeb = """
                    <!DOCTYPEhtml>
                        <html>
                        <head>
                            <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                            <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                        </head>
                        <style type="text/css">
                            img{
                                display:inline-block;
                                max-width:100%@;
                            }
                        </style>
                        <body style="margin:0px; background-color:#ffffff;">
                          
                            <div style="padding:14px; margin-top:10px; background-color:#ffffff;">
                                <div>
                                    <p style="font-weight: Medium; font-size:16px;">%@</p>
                                 
                                    <div style="margin-left: 0px;">
                                        <p style="font-size: 12px; margin: 0px;min-height:16px;color:#939AA8">%@</p>
                                    </div>
                                </div>
                               
                                <div style="margin-top:10px;">
                                    <img style="width:100%;" src="%@"/>
                                </div>
                                               
                                <div style="width:100%;">
                                    %@
                                 
                                </div>
                            </div>
                        </body>
                        </html>
                    """
            let timeStr = XTManageCenter.checkTimes(createDate: self.data.createdTime ?? "")
            tempStr = String(format: formatWeb,
                             "%",
                             self.data.title ?? "",
                             timeStr,
                             self.data.imageUrl ?? "",
                             self.data.content ?? ""
            )
        }else{
            tempStr = self.data.content ?? ""
        }
        return tempStr
    }
    
    ///监听进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressView.progress = Float(self.cacheWebView.estimatedProgress)
        }
        if self.cacheWebView.estimatedProgress == 1 {
            self.progressView.isHidden = true
            if self.cacheWebView.frame.size.height > 10 {
                self.emptyView.isHidden = true
            }else{
                self.willShowEmptyView()
            }
        }else{
            self.progressView.isHidden = false
        }
        
        ///监听webView.scrollview的大小
        if keyPath == "contentSize" {
            if self.cacheWebView.frame.size.height < self.cacheWebView.scrollView.contentSize.height {
                self.calculatorWebViewHeight()
            }
        }
    }
    
    ///展开webview的高度
    private func calculatorWebViewHeight(){
        let tempWebHeight = self.cacheWebView.scrollView.contentSize.height
        self.cacheWebView.frame.size.height = tempWebHeight
        self.webBkgView.frame.size = CGSize.init(width: kScreenWidth, height: tempWebHeight)
        if tempWebHeight > 10 {
            self.tableView.reloadData()
            self.emptyView.isHidden = true
        }else{
            self.willShowEmptyView()
        }
    }
    
    private func didSelectCell(indexPath: IndexPath) {
        if self.dataArr.count > indexPath.row {
            let tempHtml = self.createHtmlContentString()
            self.cacheWebView.loadHTMLString(tempHtml, baseURL: nil)
            let model = self.dataArr[indexPath.row]
//            let vc = SubscriberViewController()
//            vc.carId = "\(model.id ?? 0)"
//            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension ArticleDetailsViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let imgH = (kScreenWidth - 36) * 9/16
        return imgH + 78
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.dataArr.count > 0 {
            return 78
        }
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 78))
        header.clipsToBounds = true
        header.backgroundColor = UIColor.clear
        
        let tempBtn = UIButton.init(frame: CGRect.init(x: 18, y: 40, width: kScreenWidth - 36, height: 20))
        tempBtn.backgroundColor = UIColor.clear
        tempBtn.setTitle(MMLocalizedString("rec_car", comment: "推薦車輛"), for: .normal)
        tempBtn.setTitle(MMLocalizedString("rec_car", comment: "推薦車輛"), for: .highlighted)
        tempBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 18)
        tempBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        tempBtn.setTitleColor(Theme.titleLabColor, for: .highlighted)
        tempBtn.setImage(UIImage.init(named: "icon_assurance_arrows"), for: .normal)
        tempBtn.setImage(UIImage.init(named: "icon_assurance_arrows"), for: .highlighted)
        tempBtn.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 4, bottom: 0, right: 0)
        tempBtn.semanticContentAttribute = .forceRightToLeft
        tempBtn.contentHorizontalAlignment = .left
        header.addSubview(tempBtn)
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect.zero)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ArticelTitleTableViewCell", for: indexPath) as! ArticelTitleTableViewCell
        cell.delegate = self
        cell.indexPath = indexPath
        if self.dataArr.count > indexPath.row {
            let itemModel = self.dataArr[indexPath.row]
            cell.setFavoryCell(data: itemModel)
        }
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.didSelectCell(indexPath: indexPath)
    }
    
}

extension ArticleDetailsViewController: ArticelTitlTableCellDelegate {
    func didSelectFavoryTableCell(atIndex: IndexPath) {
        self.didSelectCell(indexPath: atIndex)
    }
}

extension ArticleDetailsViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("start")
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("finished")
    }
}
